package com.rdc.qingkou.ui;


import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.githang.statusbar.StatusBarCompat;
import com.rdc.qingkou.Application.MyApplication;
import com.rdc.qingkou.R;
import com.rdc.qingkou.adapter.LabelRecycleViewAdapter;
import com.rdc.qingkou.base.BaseActivity;
import com.rdc.qingkou.contract.SendContract;
import com.rdc.qingkou.entity.SendContentBean;
import com.rdc.qingkou.presenter.SendPresenter;
import com.rdc.qingkou.utils.LabelSharedPreferencesUtils;
import com.rdc.qingkou.widget.ProgressDialog;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;

import static com.rdc.qingkou.config.Constant.sANONFLASE;
import static com.rdc.qingkou.config.Constant.sANONTRUE;
import static com.rdc.qingkou.config.Constant.sCHOOSEALBUM;
import static com.rdc.qingkou.config.Constant.sCHOOSEMEDIA;
import static com.rdc.qingkou.config.Constant.sCUSTOMLABEL;
import static com.rdc.qingkou.config.Constant.sPLAY;
import static com.rdc.qingkou.config.Constant.sPREVIEW;
import static com.rdc.qingkou.config.Constant.sRECORD;
import static com.rdc.qingkou.config.Constant.sTAKEPHOTO;


public class SendActivity extends BaseActivity<SendPresenter> implements SendContract.View, View.OnClickListener {
    private Button mBack;
    private Button mSend;
    private EditText mContent;
    private ImageView mAddMedia;
    private ImageView mRecord;
    private ImageView mImage_Anon;
    private LinearLayout mAnonSend;
    private LinearLayout mEditMadel;
    private RecyclerView mLabel;
    private LabelRecycleViewAdapter mLabelAdapter;
    private LabelSharedPreferencesUtils mLabelUtils;
    private List<String> mLabelList;
    private List<Boolean> mBooleanList;
    private boolean mIsRecord;
    private boolean mIsAddMedia;
    private boolean mMeidaType;
    private String mImagePath;
    private String mAudioPath;
    private String mMediaPath;
    private Integer mAnonymity;
    private SendContentBean mSendContent;
    private Bundle mSave;
    private Dialog dialog;
    private Disposable mDisposable;
    private boolean  onKeyDown;
    private static final String TAG = "SendActivity";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.addActivity(this);
        setContentView(R.layout.send);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.windowBackground), true);

        initView(savedInstanceState);


        mLabelAdapter.setOnItemClickListener(new LabelRecycleViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view) {
                Intent intent = new Intent(SendActivity.this, CustomLabelDialogActivity.class);
                startActivityForResult(intent, sCUSTOMLABEL);
            }
        });

    }


    void initView(Bundle savedInstanceState) {
        mBack = (Button) findViewById(R.id.btn_back);
        mSend = (Button) findViewById(R.id.btn_send);
        mContent = (EditText) findViewById(R.id.et_content);
        mAddMedia = (ImageView) findViewById(R.id.iv_addmedia);
        mRecord = (ImageView) findViewById(R.id.iv_record);
        mAnonSend = (LinearLayout) findViewById(R.id.linearlayout_anonSend);
        mEditMadel = (LinearLayout) findViewById(R.id.linearlayout_edit_model);
        mImage_Anon = (ImageView) findViewById(R.id.imbtn_anon);
        mLabel = (RecyclerView) findViewById(R.id.rv_label);

        dialog = ProgressDialog.createLoadingDialog(this);



        mAnonSend.setOnClickListener(this);
        mEditMadel.setOnClickListener(this);
        mAddMedia.setOnClickListener(this);
        mRecord.setOnClickListener(this);
        mBack.setOnClickListener(this);
        mSend.setOnClickListener(this);

        mLabelList = new ArrayList<>();
        mLabelList.add("");
        mLabelList.add("原创");
        mLabelList.add("摘录");
        mLabelList.add("音乐");
        mLabelList.add("影视");
        mLabelList.add("");
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mLabel.setLayoutManager(layoutManager);
        mLabelAdapter = new LabelRecycleViewAdapter(mLabelList);
        mLabel.setAdapter(mLabelAdapter);
        mLabelUtils = new LabelSharedPreferencesUtils(this);

        mBooleanList = new ArrayList<>();

        mAnonymity = sANONFLASE;
        mMeidaType = true;
        mImagePath = "";
        mAudioPath = "";
        mMediaPath = "";
        mIsRecord = false;
        mIsAddMedia = false;
        mSendContent = new SendContentBean();

        if (savedInstanceState != null) {
            mSave = savedInstanceState;
            if (!TextUtils.isEmpty(mSave.getString("content"))) {
                mContent.setText(mSave.getString("content"));

            }
            mLabelList = mSave.getStringArrayList("tagStr");
            mLabelAdapter = new LabelRecycleViewAdapter(mLabelList);
            mLabel.setAdapter(mLabelAdapter);
            if (mSave.getInt("anon") == sANONTRUE) {
                mAnonymity = sANONTRUE;
                mAnonSend.setSelected(true);
            }
        }


    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //添加视频图片/或者预览视频图片
            case R.id.iv_addmedia:
                if (!mIsAddMedia) {
                    Intent intent = new Intent(this, ChooseImageDialogActivity.class);
                    startActivityForResult(intent, sCHOOSEMEDIA);
                } else {
                    Intent intent = new Intent(this, PreviewDialogActivity.class);
                    intent.putExtra("MediaPath", mMediaPath);
                    startActivityForResult(intent, sPREVIEW);

                }
                break;

            //录音或者播放录音
            case R.id.iv_record:
                if (!mIsRecord) {
                    Intent intent = new Intent(this, RecordDialogActivity.class);
                    startActivityForResult(intent, sRECORD);
                } else {
                    Intent intent = new Intent(this, PlayDialogActivity.class);
                    intent.putExtra("FilePath", mAudioPath);
                    startActivityForResult(intent, sPLAY);
                }
                break;

            //匿名/公开
            case R.id.linearlayout_anonSend:
                if (mAnonymity == sANONFLASE) {
                    mImage_Anon.setBackgroundResource(R.drawable.button_anon_on);
                    mAnonymity = sANONTRUE;
                } else {
                    mImage_Anon.setBackgroundResource(R.drawable.button_anon_off);
                    mAnonymity = sANONFLASE;

                }
                break;

            //编辑模板
            case R.id.linearlayout_edit_model:
                Intent intent = new Intent(this, TemplateActivity.class);
                startActivity(intent);
                break;


            case R.id.btn_back:
                finish();
                break;

            case R.id.btn_send:

                   if (!TextUtils.isEmpty(mContent.getText())){
                       mSendContent.setmContent(mContent.getText().toString());
                       if (mRecord.getVisibility() == View.INVISIBLE) {
                           mAudioPath = "";
                       }
                       mBooleanList = mLabelAdapter.getmFlag();
                       ArrayList<String> tag = new ArrayList<>();
                       for (int i = 0; i < mLabelList.size() - 1; i++) {
                           if (mBooleanList.get(i)) {
                               tag.add(mLabelList.get(i));

                           }
                       }
                       mSendContent.setmMediaFile(mMediaPath);
                       mSendContent.setmVoiceFile(mAudioPath);
                       mSendContent.setmLabel(tag);
                       mSendContent.setMediaType(mMeidaType);
                       mSendContent.setAnonymity(mAnonymity);
                       mPresenter.send();

                   }else {
                       Toast.makeText(this,"内容不能为空哦!",Toast.LENGTH_SHORT).show();
                   }

                break;


        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case sCHOOSEMEDIA:
                if (resultCode == RESULT_OK) {
                    if (data.getStringExtra("DOWN").equals("takePhoto")) {
                        mPresenter.takePhoto();

                    }
                    if (data.getStringExtra("DOWN").equals("chooseAlbum")) {
                        if (ContextCompat.checkSelfPermission(this,
                                android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions(this,
                                    new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                        } else {
                            mPresenter.chooseAlbum();
                        }
                    }
                }
                break;
            case sRECORD:
            case sPLAY:
                if (resultCode == RESULT_OK) {
                    playOrRecord(data.getStringExtra("AudioFile"));
                }
                break;
            case sTAKEPHOTO:
                if (resultCode == RESULT_OK) {

                    setPhotoImage();
                }
                break;
            case sCHOOSEALBUM:
                if (resultCode == RESULT_OK) {
                    mPresenter.setAlbumPhoto(data);
                }
                break;
            case sCUSTOMLABEL:
                if (resultCode == RESULT_OK) {
                    addLabel(data.getStringExtra("CustomLabel"));

                }
                break;

            case sPREVIEW:
                if (resultCode == RESULT_OK) {
                    preview(data.getStringExtra("MediaPath"));

                }
            default:


        }
    }

    @Override
    public void jumpToHomePage() {
        Intent intent = new Intent(this, HomepageActivity.class);
        startActivity(intent);
    }

    @Override
    public void takePhoto(Uri uri) {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        mMediaPath = uri.getPath();
        startActivityForResult(intent, sTAKEPHOTO);

    }

    @Override
    public void openAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/;video/");
        startActivityForResult(intent, sCHOOSEALBUM);
    }

    @Override
    public void setPhotoImage() {
        if (mSave != null) {
            mMediaPath = mSave.getString("mediaPath");
        }
        Glide.with(this).load(mMediaPath).placeholder(R.drawable.imageview_palceholder).into(mAddMedia);
        mIsAddMedia = true;
        if (mMediaPath.endsWith(".png") || mMediaPath.endsWith(".jpg") || mMediaPath.endsWith("JPEG")) {
            mMeidaType = true;

            mRecord.setVisibility(View.VISIBLE);
        } else {
            mMeidaType = false;
            mRecord.setVisibility(View.INVISIBLE);

        }
    }

    @Override
    public void addLabel(String label) {
        if (!TextUtils.isEmpty(label)) {
            int i = 0;
            for (; i < mLabelList.size() - 1; i++) {
                if (mLabelList.get(i).equals(label)) {
                    break;
                }
            }
            if (i == mLabelList.size() - 1) {
                mLabelList.remove(mLabelList.size() - 1);
                mLabelList.add(label);
                mLabelList.add("");
                mLabelAdapter.notifyDataSetChanged();
                mLabelUtils.putString(label);
            }

        }


    }

    @Override
    public void preview(String data) {
        if (TextUtils.isEmpty(data)) {
            mIsAddMedia = false;
            mAddMedia = (ImageView) findViewById(R.id.iv_addmedia);
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.imageview_addmedia);
            mAddMedia.setImageBitmap(bitmap);
            mMediaPath = "";
            mRecord.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void playOrRecord(String data) {
        if (!TextUtils.isEmpty(data)) {
            mAudioPath = data;
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.imageview_recoding_allready);
            mRecord.setImageBitmap(bitmap);
            mIsRecord = true;
        } else {
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.imageview_recording);
            mRecord.setImageBitmap(bitmap);
            mIsRecord = false;
            mAudioPath = "";

        }
    }

    @Override
    public void setAlbumImage(String imagePath) {
        mImagePath = imagePath;
        mMediaPath = mImagePath;
        Glide.with(this).load(mImagePath).placeholder(R.drawable.imageview_palceholder).into(mAddMedia);
        mIsAddMedia = true;
        if (mMediaPath.endsWith(".png") || mMediaPath.endsWith(".jpg") || mMediaPath.endsWith("JPEG")) {
            mMeidaType = true;

            mRecord.setVisibility(View.VISIBLE);

        } else {
            mMeidaType = false;
            mRecord.setVisibility(View.INVISIBLE);
        }
    }


    @Override
    public SendPresenter getInstance() {
        return new SendPresenter();
    }

    @Override
    public SendContentBean getSendBean() {
        return mSendContent;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("mediaPath", mMediaPath);
        outState.putString("audioPath",mAudioPath);
        boolean[] tagCheckBox  = new boolean[mLabelList.size()];
        mBooleanList = mLabelAdapter.getmFlag();
        for (int i = 0; i < mLabelList.size() - 1; i++) {
           tagCheckBox[i] = mBooleanList.get(i);
        }
        outState.putBooleanArray("tagCheckBox",tagCheckBox);

        outState.putStringArrayList("tagStr",(ArrayList<String>) mLabelList);
        outState.putInt("anon",mAnonymity);
        outState.putString("content",mContent.getText().toString());


    }

    @Override
    public void showLoadingDialog() {
          runOnUiThread(new Runnable() {
              @Override
              public void run() {
                  dialog.show();
              }
          });



    }

    @Override
    public void dimissLoadingDialog() {
        dialog.dismiss();
    }

    @Override
    public void showFailure() {
        Toast.makeText(this,"发送失败",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void finishActivity() {
        finish();
    }

    @Override
    public void setDisposable(Disposable disposable) {
        if (mDisposable!=null&&mDisposable.isDisposed()){
            mDisposable.dispose();

        }
        mDisposable = disposable;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {


        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mDisposable != null && mDisposable.isDisposed()) {
                mDisposable.dispose();
                onKeyDown = false;
                Log.e(TAG, "onKeyDown: back" + onKeyDown);

            } else {
                onKeyDown = super.onKeyDown(keyCode, event);
                Log.e(TAG, "onKeyDown:super" + onKeyDown);
            }


        }
        return onKeyDown;
    }
    @Override
    protected void onStop() {
        super.onStop();
        if (mDisposable!=null&&mDisposable.isDisposed()){
            mDisposable.dispose();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDisposable!=null&&mDisposable.isDisposed()){
             mDisposable.dispose();
        }
    }
}
